<template>
  <div class="postPublish">
    <!-- 面包屑部分 -->
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/postlist' }">文章管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/postPublish' }">文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片显示 -->
    <el-card class="box-card" style="margin-top : 20px">
      <!-- 文本框 -->
      <el-form ref="postPublish" :model="post" label-width="80px">
        <el-form-item label="标题:">
          <el-input v-model="post.title"></el-input>
        </el-form-item>
        <!-- 单选框 -->
        <el-form-item label="类型:">
          <el-radio-group v-model="post.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 中间内容部分 -->
        <el-form-item label="内容:">
          <!-- 富文本框 -->
          <VueEditor :config="config" ref="vueEditor" v-if="post.type===1" />
          <!-- 文件上传组件 -->
          <el-upload
            class="upload-demo"
            action="http://localhost:3000/upload"
            :headers="getToken()"
            :on-success="headlerSuccess"
            v-if="post.type===2"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
          </el-upload>
        </el-form-item>
        <!-- 栏目---复选框部分 -->
        <el-form-item label="栏目:">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <!-- 下面选择的单选框 -->
          <el-checkbox-group v-model="post.categories" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="cate in cateList" :label="cate.id" :key="cate.id">{{cate.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 封面部分  -->
        <el-form-item label="封面:">
          <!-- file-list就是当前文件上传组件中的已上传文件的列表 -->
          <el-upload
            action="http://localhost:3000/upload"
            list-type="picture-card"
            :headers="getToken()"
            :on-success="headlerCover"
            :on-remove="removeCover"
            :file-list="post.cover"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- 底部提交按钮 -->
        <el-button
          type="primary"
          @click="publishPost"
          style="margin-bottom:20px; margin-right:30px; float: right;"
        >{{btn}}</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 引入富文本框
import VueEditor from 'vue-word-editor';
import 'quill/dist/quill.snow.css';
import {
  getCateList,
  publishPost,
  getArticleById,
  eidArticleById
} from '../apis/article';

export default {
  components: {
    VueEditor
  },
  data() {
    return {
      btn: '发布文章',
      isIndeterminate: false,
      checkAll: false,
      cateList: [],
      // 服务器默认参数
      post: {
        title: '',
        content: '',
        categories: [],
        cover: [],
        type: 1
      },
      // 富文本框的基本配置
      config: {
        // 上传图片的配置
        uploadImage: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.data.url);
          },
          headers: this.getToken()
        },

        // 上传视频的配置
        uploadVideo: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.data.url);
          },
          headers: this.getToken()
        }
      }
    };
  },
  methods: {
    // 上传视频文件成功的函数
    headlerSuccess(response, file, fileList) {
      // console.log(response);
      if (response.message === '文件上传成功') {
        this.post.content = 'http://127.0.0.1:3000' + response.data.url;
      }
    },
    //   点击全选，全不选的样式
    handleCheckAllChange(val) {
      // console.log(val)
      this.post.categories = val
        ? this.cateList.map(value => {
          return value.id;
        })
        : [];
      // 现在的状态是一个确定的状态：全选|全不选
      this.isIndeterminate = false;
      // console.log(this.cateList)
      // console.log(this.post.categories)
    },
    // 单击某个文本框触发的事件
    handleCheckedCitiesChange(value) {
      // console.log(value)
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
    // 上传封面成功的函数
    headlerCover(response) {
      if (this.$route.params.id) {
        if (response.message === '文件上传成功') {
          response.data.url = 'http://127.0.0.1:3000' + response.data.url
          this.post.cover.push({ id: response.data.id, url: response.data.url });
        }
      } else {
        if (response.message === '文件上传成功') {
          this.post.cover.push({ id: response.data.id });
        }
      }
    },
    // 删除封面的函数
    removeCover(file) {
      let id
      if (this.$route.params.id) {
        console.log(file)
        id = file.id
      } else {
        // console.log(file)
        id = file.response.data.id;
      }
      for (let i = 0; i < this.post.cover.length; i++) {
        if (this.post.cover[i].id === id) {
          this.post.cover.splice(i, 1);
          break;
        }
      }
    },
    // 封装token的拦截器
    getToken() {
      let token = localStorage.getItem('heima_toutiao_token');
      return { Authorization: token };
    },
    // 点击提交按钮实现发布文章(编辑文章)
    async publishPost() {
      let res = 0
      if (this.$route.params.id) {
        // 编辑文章
        let id = this.$route.params.id;
        // 改造栏目数据
        this.post.categories = this.post.categories.map(value => {
          return { id: value }
        })
        res = await eidArticleById(id, this.post)
        // console.log(res)
        if (res.data.message === '文章编辑成功') {
          this.$message.success('文章发布成功');
          this.$router.push({ name: 'Postlist' });
        }
      } else {
        console.log(this.post);
        // 点击提交拿富文本框数据
        if (this.post.type === 1) {
          this.post.content = this.$refs.vueEditor.editor.root.innerHTML;
        }
        // 改造栏目数据类型
        this.post.categories = this.post.categories.map(value => {
          return { id: value };
        });
        // 发请求
        res = await publishPost(this.post);
        // console.log(res);
        if (res.data.message === '文章发布成功') {
          this.$message.success('文章发布成功');
          this.$router.push({ name: 'Postlist' });
        }
      }
    }
  },
  //   获得服务器栏目数据
  async mounted() {
    let res = await getCateList();
    // console.log(res)
    if (localStorage.getItem('heima_toutiao_token')) {
      this.cateList = res.data.data.splice(2);
    } else {
      this.cateList = res.data.data.splice(1);
    }

    // 文章编辑部分
    if (this.$route.params.id) {
      this.btn = '编辑文章'
      let id = this.$route.params.id; // 获取可能传递的参数
      if (id) {
        let res1 = await getArticleById(id);
        console.log(res1);
        // 标题和类型直接双向绑定渲染完成
        this.post = res1.data.data;
      }
      // 父文本框的动态渲染
      if (this.post.type === 1) {
        var quill = this.$refs.vueEditor.editor;
        quill.clipboard.dangerouslyPasteHTML(0, this.post.content);
      }
      // 栏目的动态渲染
      this.post.categories = this.post.categories.map(value => {
        return value.id;
      });
      if (
        this.post.categories.length === this.cateList.length ||
      this.post.categories.length
      ) {
        this.isIndeterminate = false; // 说明栏目为全选或者全不选
      }
      // 处理封面
      this.post.cover = this.post.cover.map(v => {
        return {
          id: v.id,
          url: v.url
        }
      })
      // 封面的动态渲染
      this.post.cover.forEach(value => {
        if (value.url.indexOf('http') === -1) {
          value.url = 'http://127.0.0.1:3000' + value.url;
        }
      });
    }
  }
};
</script>

<style>
</style>
